package timing.ukulele.web.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.thread.threadlocal.NamedThreadLocal;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import timing.ukulele.common.constant.ExceptionConstant;
import timing.ukulele.common.exception.NoOperatorException;
import timing.ukulele.web.model.OperatorInfo;

import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * @author fengxici
 */
@Slf4j
public class RequestUtil {
    private RequestUtil() {
        throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS);
    }

    private static final ThreadLocal<OperatorInfo> authInfoLocal = new NamedThreadLocal<>("RequestOperatorInfo");

    /**
     * 从 Request 中获取指定 Key 的 Header 值
     *
     * @param request {@link HttpServletRequest}
     * @param key     Header Name
     * @return Header Value
     */
    public static String getRequestHeader(HttpServletRequest request, String key) {
        return request.getHeader(key);
    }

    /**
     * 获取设置操作人信息
     *
     * @return {@link OperatorInfo}
     */
    public static OperatorInfo getOperator() {
        OperatorInfo info = authInfoLocal.get();
        if (ObjectUtil.isNull(info)) {
            throw new NoOperatorException("Unable to get operator info");
        }

        if (ObjectUtil.isEmpty(info.getTenantId())) {
            throw new NoOperatorException("Unable to get tenant id of operator info");
        }

        if (CharSequenceUtil.isEmpty(info.getUsername())) {
            throw new NoOperatorException("Unable to get username of operator info");
        }

        if (ObjectUtil.isNull(info.getUserId())) {
            throw new NoOperatorException("Unable to get userId of operator info");
        }

        return info;
    }

    /**
     * 设置操作人信息
     *
     * @param info {@link OperatorInfo}
     */
    public static void setOperator(@Nullable OperatorInfo info) {
        if (ObjectUtil.isNull(info)) {
            resetOperator();
        } else {
            authInfoLocal.set(info);
        }
    }

    /**
     * 重置操作人
     */
    public static void resetOperator() {
        authInfoLocal.remove();
    }

    /**
     * 获取客户端ip地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    assert inet != null;
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            // "***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) {
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }

}
